﻿/*
* 创建者：LIYINFAI
* 创建时间：2023/10/24 9:35:26
* 描述：
* --------------------------------------
* 修改说明：
* --------------------------------------
*/
using CommonLibrary;
using System;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SCADA
{
    internal static class Program
    {
        public static Icon ICON = CommonLibrary.Resources.Resource.app;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            SyncDBConnect();
            #region 确保只打开一个应用程序
            Process Instance = RunningInstance();          //一次打开一个程序
            if (Instance != null)
            {
                if (Instance.MainWindowHandle.ToInt32() == 0)       //程序是否托盘化
                {
                    HWMessageBox.Show(null, "程或已打开并托盘化或进程尚未结束，请确保单独运行一个程序");
                    Application.Exit();
                    return;
                }
                HandleRunningInstance(Instance);
                HWMessageBox.Show(null, "程序已打开或者进程尚未结束，请确保单独运行一个程序");
                Application.Exit();
                return;
            }
            #endregion

            #region 全局异常捕获
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            //处理UI线程异常
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            //处理未捕获的异常
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            #endregion
            //进程退出事件
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
            GlobalStatus.PROGRAM = EAppStatus.RUN;
            Application.Run(new FormLogin());
        }
        /// <summary>
        /// 进程退出触发事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            GlobalStatus.PROGRAM = EAppStatus.STOP;
            System.Environment.Exit(0);
        }
        #region 确保只打开一个应用程序
        /// <summary>
        /// 确保只运行一个线程
        /// </summary>
        /// <returns></returns>
        private static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            foreach (Process process in processes)
            {
                if (process.Id != current.Id)
                {
                    if (process.MainModule.FileName == current.MainModule.FileName)
                    {
                        return process;
                    }
                }
            }
            return null;
        }
        private static void HandleRunningInstance(Process instance)
        {
            ShowWindowAsync(instance.MainWindowHandle, 1);
            SetForegroundWindow(instance.MainWindowHandle);
        }
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(System.IntPtr hWnd);
        #endregion

        #region 全局异常捕获
        /// <summary>
        /// 异常捕捉
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            string str = GetExceptionMsg(e.Exception, e.ToString());
            LogHelper.Error(e.Exception);
            HWMessageBox.Show(null, str, "程序异常");
        }
        /// <summary>
        /// 未处理异常事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString());
            LogHelper.Error(e.ExceptionObject as Exception);
            HWMessageBox.Show(null, str, "程序异常");
        }
        /// <summary>
        /// 获取异常信息
        /// </summary>
        /// <param name="ex">异常对象</param>
        /// <param name="backStr">未处理异常信息</param>
        /// <returns></returns>
        static string GetExceptionMsg(Exception ex, string backStr)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append($"【出现时间】：{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}");
            if (ex != null)
            {
                sb.Append($"【异常类型】：{ex.GetType().Name}");
                sb.Append($"【异常信息】：{ex.Message}");
                sb.Append($"【堆栈调用】：{ex.StackTrace}");
                sb.Append($"【异常方法】：{ex.TargetSite}");
            }
            else
            {
                sb.Append($"【未处理异常】：{backStr}");
            }
            return sb.ToString();
        }
        #endregion 全局异常捕获

        private static void SyncDBConnect()
        {
            Task.Run(() => {
                try
                {
                    using (UserSQLiteDb db = UserSQLiteDb.Instance())
                    {
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                }
                try
                {
                    using (ProductSQLiteDb db = ProductSQLiteDb.Instance(DateTime.Today.Year))
                    {
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                }
            });
        }
    }
}
